"""
netc.py

Created by  on 2007-11-02.

"""

from socket import *

#All-purpose UDP connection
class UDPConn:
    buffer = 1024               #Default buffer size
    
    def __init__(self, in_port, out_port):
        self.in_port = in_port          #Socket's bound port
        self.out_port = out_port        #Socket's send port
        
        self.sock = socket(AF_INET, SOCK_DGRAM)
        self.sock.bind(("127.0.0.1", in_port))
        self.sock.setblocking(0)
        
    #Send a string of data to an IP address
    def send_data(self, data, addr):
        #print "sent:"+(data, (addr, self.out_port))
        self.sock.sendto(data, (addr, self.out_port))
            
    #Get all data received from all sources so far.
    #Returns in format [(data1, addr1), ...]
    def recv_all_data(self):
        datalist = []
        #data, addr = None, None
        try:
            data, addr = self.sock.recvfrom(self.buffer)
            #if data is not "":
                #print data
            while data:
                datalist.append((data, addr[0]))
                try:
                    data, addr = self.sock.recvfrom(self.buffer)
                except:
                    data, addr = None, None
        except:
            pass
        return datalist
        
    #Send all messages in format [(data1, addr1), ...]
    def send_data_list(self, datalist):
        for data, addr in datalist:
            self.send_data(data, addr)